package com.it.fastpay.scheduled;

import com.it.fastpay.service.FastPayService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class FastkillScheduled {
   /*
  定时任务
       1、@EnableScheduling 开启定时任务
       2、@Scheduled开启一个定时任务
       3、自动配置类 TaskSchedulingAutoConfiguration
        spring.task.scheduling.pool.。。。。

  异步任务
       1、@EnableAsync:开启异步任务
       2、@Async：给希望异步执行的方法标注
       3、自动配置类 TaskExecutionAutoConfiguration
        spring.task.execution.poll.。。。

使用定时任务加异步完成任务不阻塞功能
    */
    @Autowired
    private FastPayService fastPayService;

    @Autowired
    private RedissonClient redissonClient;

    //秒杀商品上架功能的锁
    private final String upload_lock = "FastPay:upload:lock";

    //TODO 保证幂等性问题
    // @Scheduled(cron = "*/5 * * * * ? ")
    @Scheduled(cron = "0 0 1/1 * * ? ")
    public void uploadFastPay() {
        //1、重复上架无需处理
        log.info("上架秒杀的商品...");

        //分布式锁
        //给uploadFastPay这个方法上锁，10s后解锁
        RLock lock = redissonClient.getLock(upload_lock);
        try {
            //加锁
            lock.lock(10, TimeUnit.SECONDS);
            fastPayService.uploadFastPay();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }


}
